package com.ai.bitcoin.contrab;

import com.ai.bitcoin.contrab.handler.CheckExpireSubCoinHandle;
import com.ai.bitcoin.contrab.handler.UserEncourageRecordHandle;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 
 * @author xd
 *
 */
@Component
public class BootStrapListener implements ApplicationListener<ApplicationEvent> {
	private static final Logger logger = LoggerFactory.getLogger(BootStrapListener.class);
	private static final Object lock = new Object();
	private static volatile Boolean first = true;

	private List<JobDetail> scheduleJobList = new ArrayList<JobDetail>();

	{
		//每隔15分钟执行一次,“0”表示为从“0”分开始, “3/20”表示表示每隔20分钟执行一次，“3”表示从第3分钟开始执行
		scheduleJobList.add(new JobDetail("subcoin_expire_check",CheckExpireSubCoinHandle.class,"0 0/30 * * * ?",""));
		//7点钟开始执行
//		scheduleJobList.add(new JobDetail("coin_report_generate_job",MakeReportHtmlHandle.class,"0 0 7 * * ? ",""));
		//每天1点钟删除昨天用户的激励次数限制
		scheduleJobList.add(new JobDetail("user_encourage_job", UserEncourageRecordHandle.class,"0 0 3 * * ? ",""));
	}

	public void onApplicationEvent(ApplicationEvent event) {
		synchronized (lock) {
			if (first) {
				first = false;
					for (JobDetail jobDetail : scheduleJobList) {
							 try {
									QuartzTaskManager.addJob(jobDetail.getName(), jobDetail.getJobClass(), jobDetail.getCrontab());
									if (logger.isDebugEnabled()) {
										logger.debug("start job {} at server {}",jobDetail.getName(), jobDetail.getHostName());
									}
									
								} catch (Exception e) {
									logger.error("start job error", e);
								}
				}
				
			}
		}
	}

	@Data
	@AllArgsConstructor
	private static class JobDetail {

		private String name;

		private Class<?> jobClass;

		private String crontab;

		private String hostName;
	}

}
